package com.prmt.prmtdocking.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.prmt.prmtdocking.mapper.PrmtDockingMapper;
import com.prmt.prmtdocking.service.PrmtDockingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;

/**
 * 工控工商采集对接数据接口
 * @author liyang
 */
@Service
public class PrmtDockingServiceImpl implements PrmtDockingService {

    private static final Logger logger = LoggerFactory.getLogger(PrmtDockingServiceImpl.class);

    @Autowired
    private PrmtDockingMapper prmtDockingMapper;

    @Override
    @Transactional
    public String handleJson(String json) {
        logger.info(json);
        // 解析json字符信息
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(json);
            String deviceTypeCode = jsonNode.has("deviceTypeCode") ? jsonNode.get("deviceTypeCode").asText() : null;
            String serviceTypeCode = jsonNode.has("serviceTypeCode") ? jsonNode.get("serviceTypeCode").asText() : null;
            if (StringUtils.isEmpty(deviceTypeCode) || !"0820014001".equals(deviceTypeCode)) {
                throw new RuntimeException("对接数据异常");
            }
            StringBuilder stationIds = new StringBuilder();
            JsonNode tagInfosNode = jsonNode.get("tagInfos");
            if (tagInfosNode.isArray()) {
                for (JsonNode tagInfoNode : tagInfosNode) {
                    String collectDate = tagInfoNode.has("collectDate") ? tagInfoNode.get("collectDate").asText() : null;
                    String tagId = tagInfoNode.has("tagId") ? tagInfoNode.get("tagId").asText() : null;
                    String stationId = tagInfoNode.has("stationId") ? tagInfoNode.get("stationId").asText() : null;
                    String tagState = tagInfoNode.has("tagState") ? tagInfoNode.get("tagState").asText() : null;
                    String tagValue = tagInfoNode.has("tagValue") ? tagInfoNode.get("tagValue").asText() : null;
                    String upDate = tagInfoNode.has("upDate") ? tagInfoNode.get("upDate").asText() : null;
                    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
                    DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    if (!StringUtils.isEmpty(collectDate)) {
                        LocalDateTime collectDateTime = LocalDateTime.parse(collectDate, inputFormatter);
                        collectDate = collectDateTime.format(outputFormatter);
                    }
                    if (!StringUtils.isEmpty(upDate)) {
                        LocalDateTime upDateTime = LocalDateTime.parse(upDate, inputFormatter);
                        upDate = upDateTime.format(outputFormatter);
                    }
                    stationIds.append(" ").append(stationId);
                    // 1、更新探头档案表GS_DraughtInfo
                    prmtDockingMapper.updateDraughtInfo(tagId + "-T01", upDate, tagState, tagValue, collectDate);
                    // 2、插入历史数据表  GS_RunData
                    prmtDockingMapper.insertRunData(tagId + "-T01", upDate, tagState, tagValue, collectDate);
                    // 3、插入报警记录数据表  GS_AlertData
                    assert tagState != null;
                    if (!"正常".equals(tagState)) {
                        // 插入报警记录数据表
                        prmtDockingMapper.insertAlertData(tagId + "-T01", tagState);
                    } else {
                        // 更新报警记录数据表
                        prmtDockingMapper.updateAlertData(tagId + "-T01");
                    }
                    //更新控制器档案表 alertor
                    prmtDockingMapper.updateAlertor(tagId, tagState, tagValue, collectDate);
                }
            }
            return toJsonData("200", "上传成功", deviceTypeCode, serviceTypeCode, stationIds.toString());
        } catch (JsonProcessingException e) {
            return toJsonData("500", "上传失败", null, null, null);
        }
    }


    // 封装响应体信息
    public String toJsonData(String code, String msg, String deviceTypeCode, String serviceTypeCode, String stationId) {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("code", code);
        jsonObj.put("msg", msg);
        jsonObj.put("deviceTypeCode", deviceTypeCode);
        jsonObj.put("serviceTypeCode", serviceTypeCode);
        jsonObj.put("stationId", stationId);
        jsonObj.put("otherInfos", Collections.emptyList());
        return JSONObject.toJSONString(jsonObj);
    }
}
